package login.android;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import login.android.R.menu;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.location.LocationManager;
import android.net.Uri;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Menu extends Activity{
	private static final int MNU_OPC2 = 2;
	private static final int MNU_OPC3 = 3;
	private static final int SMNU_OPC1 = 1;
	private static final int SMNU_OPC2 = 2;
	private static final int SMNU_OPC3 = 3;
	private static final int SMNU_OPC4 = 4;
	private static final int SMNU_OPC5 = 5;
	private static final int SMNU_OPC6 = 6;
	private static final int SMNU_OPC7 = 7;
	private static int TAKE_PICTURE = 1;
	private String name = "";
	boolean sdDisponible = false;
	boolean sdAccesoEscritura = false;
	private String lic;
	private String vis;
	ImageButton tf;
	EditText un;
	LocationFinder locManager;
	//AlertDialog alerta= new AlertDialog.Builder(Menu.this).create();

	CharSequence text = "Entra SD!";
	CharSequence text2 = "Entra Memoria!";
	int duration = Toast.LENGTH_SHORT;


	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);


		//Comprobamos el estado de la memoria externa (tarjeta SD)
		//compruebaSD();

		tf = (ImageButton)findViewById(R.id.t_foto);
		un=(EditText)findViewById(R.id.et_un);
		//boton tomar foto
		/*tf.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Context context = getApplicationContext();

				try {
					//Iniciamos el intent de la camara
					Intent intent =  new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					int code = TAKE_PICTURE;

					if (sdDisponible == true){
						//Creamos el archivo donde guardaremos la captura
						Uri output = Uri.fromFile(new File(name));
						intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
						Toast toast = Toast.makeText(context, "guarda archivo", duration);
						toast.show();
					}else{
						try
						{
							Toast toast = Toast.makeText(context, text2, duration);
							toast.show();
							OutputStreamWriter fout=
									new OutputStreamWriter(
											openFileOutput("android_foto.jpg", Context.MODE_PRIVATE));

							fout.write(name);
							fout.close();
						}
						catch (Exception ex)
						{
							Log.e("Ficheros", "Error al escribir fichero a memoria interna");
						}
					}

					startActivityForResult(intent, code);
					//startActivity(intent);
				} catch (Exception e) {
					un.setText(e.toString());
				}

			}


		});*/
		name = "/mnt/sdcard/Download/foto.jpg";
		tf.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				//Context context = getApplicationContext();
				try {
					File file = new File(name);
			        Uri outputFileUri = Uri.fromFile(file);
			        Intent intent = new Intent(
			                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
			        
					startActivityForResult(intent, 1);
				} catch (Exception e) {
					un.setText(e.toString());
				}

			}


		});


	}
	@Override
	//Una vez tomada la foto recuperamos la imagen de la camara
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*Context context = getApplicationContext();
		if (requestCode == TAKE_PICTURE) {

			 // Si se reciben datos en el intent tenemos una vista previa (thumbnail)

			Toast toast3 = Toast.makeText(context, "Entra aqui", duration);
			toast3.show();
			if (data != null) {
				
				
				envioFoto(name);
				enviaLicyVis(); 
				Toast toast34 = Toast.makeText(context, "Se ha enviado la foto", duration);
				toast3.show();

				 // De lo contrario es una imagen completa
  			
			} else {

				 //A partir del nombre del archivo ya definido lo buscamos y creamos el bitmap
				 //para el ImageView

				//ImageView iv = (ImageView)findViewById(R.id.imgView);
	   			//iv.setImageBitmap(BitmapFactory.decodeFile(name));
				envioFoto(name);
				enviaLicyVis();


			}
		}*/
		System.gc();
        if (resultCode == Activity.RESULT_OK) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                Bitmap imageBitmap = BitmapFactory.decodeFile(name, options);
                envioFoto(name);
            } catch (Exception e) {
                Toast.makeText(this, "Picture Not taken",
                                Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }

	}
	//guardar los parametros de  licencias
	public void guardarConfigLic(String licencia){
		
		SharedPreferences prefs = getSharedPreferences("ficheroconfiguracion", Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = prefs.edit();
        editor.putString("licencia", licencia);
        editor.commit();
	}
	//guardar los parametros de visibilidad 
	public void guardarConfigVis( String visibilidad){

		SharedPreferences prefs = getSharedPreferences("ficheroconfiguracion", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("visibilidad", visibilidad);
		editor.commit();
	}

	
	//carga los parametros de visibilidad y licencias
	public void cargarConfig(){
		SharedPreferences prefs = getSharedPreferences("ficheroconfiguracion", Context.MODE_PRIVATE);
		
    	lic = prefs.getString("licencia", lic );
        vis = prefs.getString("visibilidad", vis);
        if (lic == "" )
			lic = "1";
        if (vis == "")
        	vis = "1";
	}
	public void enviaLicyVis(){
		
		cargarConfig();
		
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    	postParameters.add(new BasicNameValuePair("licencia", lic));
    	postParameters.add(new BasicNameValuePair("visibilidad", vis));

    	String response = null;
    	try {
    	    response = CustomHttpClient.executeHttpPost("http://proyecto.cambiarbolivarescomprareuros.com/wordpress/android/subirimagen.php", postParameters);
    	    String res=response.toString();
    	    res= res.replaceAll("\\s+","");
    	    if(res.equals("1")){
    	   
    	    }else{
    	    	
    	    }
    	} catch (Exception e) {
    		
    	}
    		
	}
	//guardar configuracion aplicacion Android usando SharedPreferences
	public void cerrarSesion() {
		SharedPreferences prefs = getSharedPreferences("ficheroconfiguracion", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("username", "");
		editor.putString("password", "");
		editor.commit();
		super.onDestroy();
	}
	
	public void compruebaSD(){
		String estado = Environment.getExternalStorageState();
		Context context = getApplicationContext();
		if (estado.equals(Environment.MEDIA_MOUNTED))
		{
			sdDisponible = true;
			sdAccesoEscritura = true;
		}
		else if (estado.equals(Environment.MEDIA_MOUNTED_READ_ONLY))
		{
			sdDisponible = true;
			sdAccesoEscritura = false;
		}
		else
		{
			sdDisponible = false;
			sdAccesoEscritura = false;
		}
		if (sdDisponible == true){
			Toast toast = Toast.makeText(context, "comprueba SD", duration);
			toast.show();
			/*File file=new File(Environment.DIRECTORY_DOWNLOADS);
			if(!file.exists())
				file.mkdirs();*/
			name = "/android_foto.jpg";
			Toast toast2 = Toast.makeText(context, name, duration);
			toast2.show();
		}else{
			Toast toast = Toast.makeText(context, text2, duration);
			toast.show();
			name = Environment.getDataDirectory() +"/android_foto.jpg";
		}
	}
	public int envioFoto(String pathToOurFile){
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		DataInputStream inputStream = null;
		
		/*String pathToOurFile = "/data/file_to_send.mp3";*/
		String urlServer = "http://proyecto.cambiarbolivarescomprareuros.com/wordpress/android/subirimagen.php";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary =  "*****";

		int serverResponseCode = 0;
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1*1024*1024;

		try
		{
			FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();

			// Allow Inputs & Outputs
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			// Enable POST method
			connection.setRequestMethod("POST");

			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

			outputStream = new DataOutputStream( connection.getOutputStream() );
			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
			outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
			outputStream.writeBytes(lineEnd);

			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0)
			{
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// Responses from the server (code and message)
			serverResponseCode = connection.getResponseCode();
			String serverResponseMessage = connection.getResponseMessage();
			Toast toast = Toast.makeText(getBaseContext(), serverResponseMessage, duration);
			toast.show();
			
			fileInputStream.close();
			outputStream.flush();
			outputStream.close();
		}
		catch (Exception ex)
		{
			//Exception handling
		}finally 
		{
			return serverResponseCode;
		}


	}
	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		//Alternativa 1
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu1,  menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.MnuOpc1:
			cerrarSesion();

			Intent intent2 =  new Intent( Menu.this, LoginLayout.class);
			startActivity(intent2);
			
			return true;
		case R.id.SubMnuOpc1:
			lic = "1";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnuOpc2:
			lic = "2";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnuOpc3:
			lic = "3";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnuOpc4:
			lic = "4";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnuOpc5:
			lic = "5";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnuOpc6:
			lic = "6";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnuOpc7:
			lic = "7";
			guardarConfigLic(lic);
			return true;
		case R.id.SubMnu2Opc1:
			vis = "1";
			guardarConfigVis(vis);
			return true;
		case R.id.SubMnu2Opc2:
			vis = "2";
			guardarConfigVis(vis);
			return true;
		case R.id.SubMnu2Opc3:
			vis = "3";
			guardarConfigVis(vis);
			return true;	
		default:
			return super.onOptionsItemSelected(item);
		}
	}


}
